package com.rskj.cashbook.iexception;

import com.rskj.cashbook.response.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Arrays;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class RestControllerAdviceExceptionHandler {

    /**
     * Token过期异常处理
     */
    @ExceptionHandler(value = TokenExpiredException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> tokenExpiredExceptionHandler(TokenExpiredException e) {
        log.warn("Token过期: {}", e.getMessage());
        return ResponseEntity.fail("token过期");
    }

    /**
     * 业务异常处理
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> businessExceptionHandler(BusinessException e) {
        log.error("业务异常: {}", e.getMessage(), e);
        return ResponseEntity.fail(e.getMessage());
    }

    /**
     * 参数校验异常处理
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> validationExceptionHandler(Exception e) {
        String message = "参数校验失败";
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            message = ex.getBindingResult().getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining(", "));
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            message = ex.getBindingResult().getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining(", "));
        }
        log.warn("参数校验异常: {}", message);
        return ResponseEntity.fail(message);
    }

    /**
     * 方法参数类型不匹配异常处理
     */
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException e) {
        String message = "参数类型不匹配: " + e.getName() + " 应该是 " + e.getRequiredType().getSimpleName();
        log.warn("参数类型不匹配异常: {}", message);
        return ResponseEntity.fail(message);
    }

    /**
     * HTTP请求方法不支持异常处理
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseEntity<String> httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e) {
        String message = "不支持的HTTP请求方法: " + e.getMethod() + 
                        "，支持的方法: " + Arrays.toString(e.getSupportedMethods());
        log.warn("HTTP请求方法不支持: {}", message);
        return ResponseEntity.fail(message);
    }

    /**
     * 找不到处理器异常处理
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> noHandlerFoundExceptionHandler(NoHandlerFoundException e) {
        String message = "找不到处理器: " + e.getHttpMethod() + " " + e.getRequestURL();
        log.warn("找不到处理器: {}", message);
        return ResponseEntity.fail("请求的接口不存在: " + e.getRequestURL());
    }

    /**
     * 数据访问异常处理
     */
    @ExceptionHandler(value = DataAccessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<String> dataAccessExceptionHandler(DataAccessException e) {
        log.error("数据访问异常: {}", e.getMessage(), e);
        return ResponseEntity.fail("数据库操作失败，请稍后重试");
    }

    /**
     * 认证异常处理
     */
    @ExceptionHandler(value = {AuthenticationException.class, BadCredentialsException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<String> authenticationExceptionHandler(Exception e) {
        log.warn("认证异常: {}", e.getMessage());
        return ResponseEntity.fail("认证失败: " + e.getMessage());
    }

    /**
     * 权限异常处理
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseEntity<String> accessDeniedExceptionHandler(AccessDeniedException e) {
        log.warn("权限异常: {}", e.getMessage());
        return ResponseEntity.fail("权限不足，无法访问该资源");
    }

    /**
     * 通用异常处理
     */
    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<String> exceptionHandler(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        log.error("异常堆栈: {}", Arrays.toString(e.getStackTrace()));
        return ResponseEntity.fail("系统内部错误，请联系管理员");
    }
}